package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.dto.SetmealDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.Setmeal;
import com.itheima.service.CategoryService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理页面
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增套餐
     */
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info("setmealDto:{}", setmealDto);
        setmealService.saveWithDish(setmealDto);
        return R.success("新增套餐成功");
    }

    /**
     * 套餐分页查询
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //创建分页构造器
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        Page<SetmealDto> dtoPage = new Page<>();

        //构建条件构造器
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        //添加查询条件
        lqw.like(name != null, Setmeal::getName, name);
        //添加排序条件
        lqw.orderByDesc(Setmeal::getUpdateTime);

        //调用分页查询
        setmealService.page(pageInfo, lqw);

        //对象拷贝,除了封装的数据（records）
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");

        //获取records的List集合
        List<Setmeal> records = pageInfo.getRecords();

        //将records中添加categoryName字段然后拷贝
        List<SetmealDto> list = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            //将基本数据先拷贝过去
            BeanUtils.copyProperties(item, setmealDto);
            //根据categoryId查找到对应categoryName
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null){
                //设置分类名称
                setmealDto.setCategoryName(category.getName());
            }
            return setmealDto;
        }).collect(Collectors.toList());

        //设置records数据字段
        dtoPage.setRecords(list);

        return R.success(dtoPage);
    }

    /**
     * 根据id进行套餐查找
     * */
    @GetMapping("/{id}")
    public R<SetmealDto> getById(@PathVariable Long id) {
        log.info("id{}",id);
        SetmealDto setmealDto = setmealService.getByIdWithDish(id);
        return R.success(setmealDto);

    }

    /**
     * 修改菜品信息
     * */
    @PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto) {
        log.info(setmealDto.toString());
        setmealService.updateWithDish(setmealDto);
        return R.success("修改套餐成功");
    }


    /**
     * 删除套餐
     * */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("ids:{}",ids);
        setmealService.removeWithDish(ids);
        return R.success("套餐数据删除成功");
    }




    /**
     * 批量停售
     * */
    @PostMapping("/status/0")
    public R<String> status(@RequestParam List<Long> ids) {
        log.info("ids:{}",ids);
        //创建条件构造器
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.in(Setmeal::getId,ids)
                .eq(Setmeal::getStatus,1);
        //判断选中的商品是否有停用的商品
        int count = setmealService.count(lqw);
        if (count > 0) {
            //获取所有选中的数据
            List<Setmeal> list = setmealService.list(lqw);
            for (Setmeal setmeal : list) {
                setmeal.setStatus(0);
            }

            setmealService.updateBatchById(list);
            return R.success("状态更改成功");
        }
        else {
            return R.error("所有选中的套餐都未起售！");
        }
    }

    /**
     * 批量起售
     * */
    @PostMapping("/status/1")
    public R<String> statusO(@RequestParam List<Long> ids) {
        log.info("ids:{}",ids);
        //创建条件构造器
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.in(Setmeal::getId,ids)
                .eq(Setmeal::getStatus,0);
        //判断选中的商品是否有停用的商品
        int count = setmealService.count(lqw);
        if (count > 0) {
            //获取所有选中的数据
            List<Setmeal> list = setmealService.list(lqw);
            for (Setmeal setmeal : list) {
                setmeal.setStatus(1);
            }

            setmealService.updateBatchById(list);
            return R.success("状态更改成功");
        }
        else {
            return R.error("所有选中的套餐都在起售中！");
        }
    }

    /**
    * 套餐页面的展示(根据条件查询)
    * */
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        //根据套餐id(categoryId)和状态（status）进行查询
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId());
        lqw.eq(setmeal.getStatus()!=null,Setmeal::getStatus,setmeal.getStatus());
        lqw.orderByDesc(Setmeal::getUpdateTime);
        
        List<Setmeal> setmealList = setmealService.list(lqw);

        return R.success(setmealList);

    }

}
